import React, { Component, Fragment } from "react";
import { Form, Input } from "antd";
import { password as passwordReg } from "@/utils/regexp";
const FormItem = Form.Item;

export default class LoginWithMsgFormItem extends Component {
  static defaultProps = {
    id: "password",
    disabled: false,
    confirm: false,
    initialValue: undefined,
    placeholder: "请输入密码",
    focus: false
  };

  constructor(props) {
    super(props);
    this.state = {
      confirmDirty: false
    };
    this.pswRef = React.createRef();
  }

  validateToNextPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && this.state.confirmDirty) {
      form.validateFields(["confirm"], { force: true });
    }
    callback();
  };

  compareToFirstPassword = (rule, value, callback) => {
    const { form, id } = this.props;
    if (value && value !== form.getFieldValue(id)) {
      callback("两次密码输入不一致");
    } else {
      callback();
    }
  };

  handleConfirmBlur = e => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  componentDidMount() {
    if (this.props.focus) this.pswRef.focus();
  }

  render() {
    const {
      form: { getFieldDecorator },
      id,
      disabled,
      initialValue,
      confirm,
      placeholder
    } = this.props;
    return (
      <Fragment>
        <FormItem>
          {getFieldDecorator(id, {
            initialValue: initialValue,
            rules: [
              {
                required: true,
                message: "密码包括6-16位大小写字母数字",
                pattern: passwordReg
              },
              {
                validator: this.validateToNextPassword
              }
            ]
          })(
            <Input
              disabled={disabled}
              className="login-input"
              type="password"
              ref={ref => (this.pswRef = ref)}
              placeholder={placeholder}
            />
          )}
        </FormItem>
        {confirm && (
          <FormItem>
            {getFieldDecorator("confirm", {
              rules: [
                {
                  required: true,
                  message: "请再次输入密码"
                },
                {
                  validator: this.compareToFirstPassword
                }
              ]
            })(
              <Input
                disabled={disabled}
                className="login-input"
                placeholder="请再次输入密码"
                type="password"
                onBlur={this.handleConfirmBlur}
              />
            )}
          </FormItem>
        )}
      </Fragment>
    );
  }
}
